package com.maycur.ctrip.util;

import com.maycur.ctrip.dto.HttpResponse;
import com.maycur.ctrip.exception.ApiException;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;



public class HttpUtil {

    public static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);


    public static <T extends HttpResponse> T httpGet(String url, Class<T> clz) throws ApiException {
        logger.info("Send the httpGet request to Ctrip with url({})", url);
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
        httpGet.setConfig(requestConfig);
        //httpGet.addHeader("Content-Type", "application/json; charset=utf-8");

        try {
            response = httpClient.execute(httpGet, new BasicHttpContext());
            return handleResponse(url, response, clz);
        } catch (IOException e) {
            logger.error("request url={}, exception={}, msg={}", url, e.getMessage(), e);
            throw new ApiException("Get an IOException when getting request", e);
        } finally {
            if (response != null)
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("The CloseableHttpResponse can't be closed!{}", e.getMessage());
                }
        }
    }

    public static <T extends HttpResponse> T httpPost(String url, Object data, Class<T> clazz)
        throws ApiException {
        logger.info("Send the httpPost request to Ctrip with url({})", url);
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/json; charset=utf-8");

        try {
            String entityData = JsonUtil.toString(data);
            if (logger.isDebugEnabled()) {
                logger.debug("The httpPost request's Entity({})", entityData);
            }

            StringEntity requestEntity = new StringEntity(entityData, "utf-8");

            httpPost.setEntity(requestEntity);

            response = httpClient.execute(httpPost, new BasicHttpContext());

            return handleResponse(url, response, clazz);
        } catch (IOException e) {
            logger.error("request url={}, exception={}, msg={}", url, e.getMessage(), e);
            throw new ApiException("Get an IOException when posting request", e);
        } finally {
            if (response != null)
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("The CloseableHttpResponse can't be closed!{}", e.getMessage());
                }
        }

    }

    private static <T extends HttpResponse> T handleResponse(String url, CloseableHttpResponse response,
        Class<T> clazz) throws IOException {
        if (response.getStatusLine().getStatusCode() != 200) {
            logger.error("request url failed, http code={}, url={}", response.getStatusLine().getStatusCode(), url);
            return null;
        }
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String resultStr = EntityUtils.toString(entity, "utf-8");
            // result = JsonUtil.parseJSON2Map(resultStr);
            if (logger.isDebugEnabled()) {
                logger.debug("Return Str: {}", resultStr);
            }
            T res = JsonUtil.toObject(resultStr, clazz);

            return res;

        }

        return null;

    }


}
